#include "fun.h"

u8 bdata com;
sbit BUZZER = com^6;
sbit RELAY = com^4;

u8 key_value = 0;

void buzzer(u8 cmd)
{
    BUZZER = cmd;
    P0 = com;
    P2 = 0xa0;
    _nop_();
    P2 = 0x00;
}

void relay(u8 cmd)
{
    RELAY = cmd;
    P0 = com;
    P2 = 0xa0;
    _nop_();
    P2 = 0x00;
}

void led(u8 ucode)
{
    P0 = ~ucode;
    P2 = 0x80;
    _nop_();
    P2 = 0x00;
}

void smg_disp(u8 num,u8 position)
{	
	P0 = 0xff;
    P2 = 0xe0;
    _nop_();
    P2 = 0x00;
	
    P0 = position;
    P2 = 0xc0;
    _nop_();
    P2 = 0x00;

    P0 = ~num;
    P2 = 0xe0;
    _nop_();
    P2 = 0x00;
}

void key_scan(void)
{
    static u8 key_up = 1;
    u16 key_value = 0;
	P44 = 0;P42 = 1;
	P35 = 1;P34 = 1;
	key_value = P3 & 0x0f;
	
	P44 = 1;P42 = 0;
	key_value = (key_value << 4) | (P3 & 0x0f);
	
    if(key_up)
    {
        P44 = 0;P42 = 1;P35 = 1;P34 = 1;
        if((P3 & 0x0f) != 0x0f)
            key_flag = 1;
        else
        {
            P44 = 1;P42 = 0;
            if((P3 & 0x0f) != 0x0f)
                key_flag = 2;
            else
            {
                P42 = 1;P35 = 0;
                if((P3 & 0x0f) != 0x0f)
                    key_flag = 3;
                else
                {
                    P35 = 1;P34 = 0;
                    if((P3 & 0x0f) != 0x0f)
                        key_flag = 4;
                    else
                        key_flag = 0;
                }
            }
        }
        if(key_flag)
        {
            key_up = 0;
            if(!P33)
                key_value = key_flag * 4;
            else if(!P32)
                key_value = key_flag * 4 + 1;
            else if(!P31)
                key_value = key_flag * 4 + 2;
            else if(!P30)
                key_value = key_flag * 4 + 3;
        }
    }
    else
    {
        if((P3 & 0x0f) == 0x0f)
            key_up = 1;
    }
}
